<?php
class Model_user extends MY_Model {

	function __construct() {
		parent::__construct();
	}


	function getData($aPost) {

		$iStart = (isset($aPost["start"]) && ($aPost["start"] != "")) ? $aPost["start"] : 0;
		$iLimit = (isset($aPost["limit"]) && ($aPost["limit"] != "")) ? $aPost["limit"] : 100;
		$sSort = (isset($aPost["sort"]) && ($aPost["sort"] != "")) ? $aPost["sort"] : "user_nume";
		$sDir = (isset($aPost["dir"]) && ($aPost["dir"] != "")) ? $aPost["dir"] : "ASC";
		$aFilters = isset($aPost["filter"]) ? json_decode($aPost["filter"]) : NULL;

		$aColumnMapping = array("user" => "user_id");

		/*if (isset($aPost["activ"]) && ($aPost["activ"] == 1)) {
			$this->db->where("available", $aPost["activ"]);
		}*/
		$this->db->select("SQL_CALC_FOUND_ROWS user_id, user_nume, user_alias, user_activ, user_email, user_rol ", FALSE);
		$this->gridFilters($sSort, $sDir, $iStart, $iLimit, $aFilters, FALSE, $aColumnMapping);
		$this->db->order_by($sSort, $sDir);
		$this->db->limit($iLimit, $iStart);
		$query = $this->db->get("nom_user");
		$totalCount = $this->db->query('SELECT FOUND_ROWS() total_rows')->row()->total_rows;
		$aData = $query->result_array();

		$data = array('totalCount' => $totalCount, 'data' => $aData);

		return $data;
	}


	/**
	 * Functie care aduce datele despre o inregistrare
	 */
	function getUser($aData) {
		$this->db->select("nom_user.*, user_rol as user_rol_val");
		$this->db->where("user_id", $aData["iRec"]);

		return $this->db->get("nom_user")->row_array();
	}


	/**
	 * Adaugare / editare
	 * @param  $aData
	 * @return bool|string
	 */
	function operation($aData) {

		$aTemp = array(
			"user_alias" => $aData["user_alias"],
			"user_nume"  => $aData["user_nume"],
			"user_email" => $aData["user_email"],
			"user_activ" => $aData["user_activ"],
			"user_rol"   => $aData["user_rol"]
		);

		//verifica duplicatele ( vezi dbase in dir library)
		$bDuplicate = $this->dbase->verifyDuplicate("nom_user", $aTemp, array("user_nume"), array("user_id" => $aData["user_id"]));
		if ($bDuplicate === TRUE) {
			return "Username duplicat!";
		}

		//insert
		if ($aData["user_id"] == 0) {
			//daca parola nu a fost introdusa atunci parola va fi username-ul
			$aTemp["user_password"] = ($aData["password"] != "") ? md5($aData["password"]) : md5($aData["user_nume"]);
			$this->db->insert("user", $aTemp);
		} else {

			if ($aData["password"] != "") {
				$aTemp["user_password"] = md5($aData["password"]);
			}

			$this->db->where("user_id", $aData["user_id"]);
			$this->db->update("nom_user", $aTemp);
		}

		return TRUE;
	}


	/**
	 * Functie care schimba parola unui user
	 */
	function addPass($aData) {
		$aUser = $this->usersession->currentUser();
		$this->db->where("user_id", $aUser['user_id']);
		$this->db->update("nom_user", array("user_password" => md5($aData['pass'])));

		return TRUE;
	}

}

?>